/**
 * Created by qunxing.du on 2016/7/27.
 * Copyright 2016 汉威.智慧环保事业部 Limited.
 * All rights reserved.
 */
package com.hw.one.collect.zzcity.memento;

import com.hw.one.collect.memento.CareTaker;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 郑州市备忘录负责人
 */
public class ZzCityCareTaker extends CareTaker<Integer, ZzCityMemento> {
    private static Map<Integer, ZzCityMemento> mementos = new ConcurrentHashMap<>();
    private final static int MAX_COUNT = 10;//拉取次数

    private ZzCityCareTaker(){}
    private static ZzCityCareTaker zzCityCareTaker;
    public static ZzCityCareTaker newInstance() {
        if(zzCityCareTaker == null){
            zzCityCareTaker = new ZzCityCareTaker();
        }
        return zzCityCareTaker;
    }
    /**
     * 添加备忘录
     *
     * @param key
     * @param memento
     */
    @Override
    public synchronized void add(Integer key, ZzCityMemento memento) {
        mementos.put(key,memento);
    }

    /**
     * 查询备忘录
     *
     * @param  key
     * @return
     */
    @Override
    public synchronized ZzCityMemento get(Integer key) {
        return mementos.get(key);
    }

    /**
     * 获取所有Memento
     *
     * @return
     */
    @Override
    public synchronized Map<Integer, ZzCityMemento> getAll() {
        return mementos;
    }

    /**
     * 移除备忘录
     *
     * @param key
     */
    @Override
    public synchronized void remove(Integer key) {
        mementos.remove(key);
    }

    /**
     * 保存或更新
     *
     * @param key
     * @param memento
     */
    @Override
    public synchronized void saveOrUpdate(Integer key, ZzCityMemento memento) {
        ZzCityMemento orginMemento = get(key);
        if(orginMemento != null){
            update(key,orginMemento);
        }else {
            add(key,memento);
        }
    }

    /**
     * 更新备忘录
     *
     * @param key
     * @param memento
     */
    @Override
    public synchronized void update(Integer key, ZzCityMemento memento) {
        int count = memento.getCount();
        //如果备忘次数超过设定次数则抛弃
        if(count >= MAX_COUNT){
            remove(key);
        }else {
            memento.setCount(++count);
            mementos.put(key,memento);
        }
    }


}
